<template>
  <div class="upload-file">
    <el-upload
      multiple
      :action="state.uploadFileUrl"
      :before-upload="handleBeforeUpload"
      :file-list="state.fileList"
      :accept="acceptFormat"
      :limit="limit"
      :on-error="handleUploadError"
      :on-exceed="handleExceed"
      :on-success="handleUploadSuccess"
      :show-file-list="false"
      :headers="state.headers"
      class="upload-file-uploader"
      ref="fileUploadRef"
      v-if="!disabled"
    >
      <!-- 上传按钮 -->
      <el-button  type="primary">选取文件</el-button>
      <!-- 上传提示 -->
      <template #tip>
          <div class="el-upload__tip" v-if="showTip">
        请上传
        <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
        <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
        的文件
      </div>
      </template>
    
    </el-upload>
    <!-- 文件列表 -->
    <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul">
      <li :key="file.url" class="el-upload-list__item ele-upload-list__item-content" v-for="(file, index) in 
      state.fileList">
      <div v-if="isImage(file.url)" class="aic jcb w100">
        <imagePreview 
        
        :src="`${state.baseUrl}${file.url}`" />
        <div class="ele-upload-list__item-content-action">
          <el-link :underline="false" @click="handleDelete(index)" type="danger" v-if="!disabled">删除</el-link>
        </div>
      </div>
          <div v-else class="aic jcb w100">
         <el-link :href="`${state.baseUrl}${file.url}`" :underline="false" target="_blank">
          <span class="el-icon-document"> {{ getFileName(file.name) }} </span>
        </el-link>
        <div class="ele-upload-list__item-content-action">
          <el-link :underline="false" @click="handleDelete(index)" type="danger" v-if="!disabled">删除</el-link>
        </div>
      </div>
      </li>
    </transition-group>
  </div>
</template>

<script setup lang="ts">
import { ElMessage } from "element-plus";
import {
  shallowRef,
  reactive,
  defineEmits,
  onBeforeMount,
  onMounted,
  watch,
  computed,
  ref,
} from "vue";
import { getToken } from "/@ts/hooks/cookie";
import { ElLoading } from "element-plus";
import imagePreview from '/@/components/ImagePreview/index.vue';
const state: any = reactive({
        number: 0,
      uploadList: [],
      baseUrl:import.meta.env.VITE_BASE_URL ,
      uploadFileUrl: import.meta.env.VITE_BASE_URL + "/common/upload", // 上传文件服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileList: [],
});
let visible = shallowRef(false);
// 在 script setup 中添加这个计算属性
const acceptFormat = computed(() => {
  const mimeTypes = {
    // 图片格式
    'png': 'image/png',
    'jpg': 'image/jpeg',
    'jpeg': 'image/jpeg',
    'gif': 'image/gif',
    'bmp': 'image/bmp',
    'webp': 'image/webp',
    // 文档格式
    'doc': 'application/msword',
    'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'xls': 'application/vnd.ms-excel',
    'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'ppt': 'application/vnd.ms-powerpoint',
    'pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
    'pdf': 'application/pdf',
    'txt': 'text/plain'
  };
  
  return prop.fileType
    .map(ext => mimeTypes[ext.toLowerCase()] || `.${ext}`)
    .join(',');
});
const emit = defineEmits(["update:modelValue"]);
const prop = defineProps({
  modelValue: {
    type: [String, Object, Array],
    
  },
   // 数量限制
    limit: {
      type: Number,
      default: 5
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 5
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["doc", "docx", "xls", "xlsx", "ppt", "pptx", "txt", "pdf"]
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    },
    // 禁用组件（仅查看文件）
    disabled: {
      type: Boolean,
      default: false
    }
});
/**
 * 判断文件后缀类型 是否是 图片
 * @param fileName 文件名
 * @returns boolean
 */
const isImage = (fileName: string): boolean => {
  // 图片格式
  const imageTypes = ['png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp'];
  // 获取文件后缀
  const extension = fileName.split('.').pop()?.toLowerCase();
  // 判断是否是图片格式
  return extension ? imageTypes.includes(extension) : false;
};

watch(
  () => prop.modelValue,
  (val: any) => {
     if (val) {
          let temp = 1;
          // 首先将值转为数组
          const list = Array.isArray(val) ? val : val.split(',');
          // 然后将数组转为对象数组
          state.fileList = list.map(item => {
            if (typeof item === "string") {
              item = { name: item, url: item };
            }
            item.uid = item.uid || new Date().getTime() + temp++;
            return item;
          });
        } else {
          state.fileList = [];
          return [];
        }
  },
  {
    deep: true,
    immediate: true,
  },
);
const loadingInstance = ref()
const handleBeforeUpload = (file) => {
       // 校检文件类型
      if (prop.fileType) {
        const fileName = file.name.split('.');
        const fileExt = fileName[fileName.length - 1];
        const isTypeOk = prop.fileType.indexOf(fileExt) >= 0;
        if (!isTypeOk) {
            ElMessage({ message: `文件格式不正确，请上传${prop.fileType.join("/")}格式文件!`, type: "error" });
          return false;
        }
      }
      // 校检文件名是否包含特殊字符
      if (file.name.includes(',')) {
         ElMessage({ message:'文件名不正确，不能包含英文逗号!', type: "error" });
        return false;
      }
      // 校检文件大小
      if (prop.fileSize) {
        const isLt = file.size / 1024 / 1024 < prop.fileSize;
        if (!isLt) {
          ElMessage({ message:`上传文件大小不能超过 ${prop.fileSize} MB!`, type: "error" });
          return false;
        }
      }
       loadingInstance.value = ElLoading.service({
    lock: true,
    text: "正在上传文件，请稍候...",
    spinner: "el-icon-loading",
    background: "rgba(0, 0, 0, 0.7)",
  });
      state.number++;
      return true;
};
const handleUploadError = () => {
  ElMessage({ message:"上传文件失败，请重试", type: "error" });
    loadingInstance.value.close()
};
    /**
     * The ready event passed to Cropper.js
     */
    function ready() {
      console.log('Cropper is ready.')
    }
const uploadedSuccessfully = () =>{
    if (state.number > 0 && state.uploadList.length === state.number) {
        state.fileList = state.fileList.concat(state.uploadList);
        state.uploadList = [];
        state.number = 0;
      
         emit("update:modelValue", listToString(state.fileList));
         loadingInstance.value.close()
      }
}
const fileUploadRef = ref()
const getFileName = (name)=>{
   if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
      } else {
        return name;
      }
}
const handleExceed = () => {
  ElMessage({ message:`上传文件数量不能超过 ${prop.limit} 个!`, type: "error" });
};
const showTip = computed(() => {
  return prop.isShowTip && (prop.fileSize || prop.fileType);
});
const handleUploadSuccess = (res, file) => {
        if (res.code === 200) {
        state.uploadList.push({ name: res.fileName, url: res.fileName });
       uploadedSuccessfully();
      } else {
        state.number--;
        loadingInstance.value.close()
          ElMessage({ message:res.msg, type: "error" });
       fileUploadRef.value.handleRemove(file);
        uploadedSuccessfully();
      }
};
const listToString = (list, separator?) => {
        let strs = "";
      separator = separator || ",";
      for (let i in list) {
        strs += list[i].url + separator;
      }
      return strs != '' ? strs.substr(0, strs.length - 1) : '';
};
const handleDelete = (index) => {
      state.fileList.splice(index, 1);
        emit("update:modelValue", listToString(state.fileList));
};
const handleClear = () => {
  emit("update:modelValue", "");
}
const handleIcon = (name: string) => {
  emit("update:modelValue", name);
};
</script>

<style scoped lang="scss">
.upload-file-uploader {
  margin-bottom: 5px;
}
.upload-file-list .el-upload-list__item {
  border: 1px solid #e4e7ed;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
}
.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}
.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}
</style>
